package com.h3bpm.web.organization.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.RestfulApi.Entity.RestfulApiResult;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.handler.JSONUtils;
import com.h3bpm.web.common.utils.SqlUtil;
import com.h3bpm.web.config.UrlConfig;
import com.h3bpm.web.organization.model.SysUser;
import com.h3bpm.web.protalHanding.OrcaleHelper;
import data.DataRow;
import data.DataTable;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author: VillWang
 * @Date: 2020/6/15 14:28
 */
@RestController
@RequestMapping("/Portal/OaUnitUser")
public class OaUnitUserController  extends ControllerBase {
    private static final Logger logger = LoggerFactory.getLogger(OaUnitUserController.class);
    @Override
    public String getFunctionCode() {
        return null;
    }
    @RequestMapping("/Unit")
    public JSONObject organizationUnit(String flag, Map<String,Object> list){

        return null;
    }
    @RequestMapping("/getUser")
    public JSONObject getUser(String userName, String jobNo){
        JSONObject result = new JSONObject();
        logger.info("业务系统获取用户数据—————userName—"+userName+"---jobNo--"+jobNo);
        String sql = "SELECT o.ObjectID,u.emp_idnumber,u.emp_id,u.emp_name,u.emp_number,u.emp_mobilephone,t.dept_content,t.dept_allcontent \n" +
                " FROM dbo_user u \n" +
                " LEFT JOIN dbo_unit t on u.dept_id=t.dept_id \n" +
                " LEFT JOIN ot_user o ON u.emp_number= o.`Code`\n" +
                " WHERE 1=1 ";
        try {
        if(StringUtils.isNotBlank(userName)&&StringUtils.isNotBlank(jobNo)){
            if(StringUtils.isNotBlank(userName)){
              sql=sql+" and u.emp_name='"+userName+"'";
            }
            if(StringUtils.isNotBlank(jobNo)){
                sql=sql+" and u.emp_number='"+jobNo+"'";
            }

            DataTable data = SqlUtil.doQuery(sql);
            List<DataRow> entityRows = data.getEntityRows();
            ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
            if(!entityRows.isEmpty()&&entityRows.size()>0) {
                for (DataRow userData : entityRows) {
                    HashMap<String, Object> map = new HashMap<>();
                    String globalId = userData.getString("emp_id");
                    String ObjectID = userData.getString("ObjectID");
                    String name = userData.getString("emp_name");
                    String no = userData.getString("emp_number");
                    String phoneNumber = userData.getString("emp_mobilephone");
                    String personnelDept = userData.getString("dept_content");
                    String idNumber = userData.getString("emp_idnumber");
                    String allcontent = userData.getString("dept_allcontent");
                   // if(allcontent.contains("同济咨询")||allcontent.contains("TJEC")){
                        map.put("globalId",globalId);
                        map.put("userName",name);
                        map.put("ObjectID",ObjectID);
                        map.put("idNumber",idNumber);
                        map.put("jobNo",no);
                        map.put("phoneNumber",phoneNumber);
                        map.put("personnelDept",personnelDept);
                        arrayList.add(map);
                   // }
                }
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("list",arrayList);
                result.put("Message","成功");
                result.put("Result",maps);
                return result;
            }

         }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改用户状态
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/modifyUserStatus", method = RequestMethod.POST)
    @ResponseBody
    public final Object enableCancelUserStatus(@RequestBody SysUser user){
        logger.info("修改用户状态,ObjectId:"+user.getObjectId()+"-----State:"+user.getState());
        if(null==user||StringUtils.isBlank(user.getObjectId())||null==user.getState()){
            return new RestfulApiResult(500,"fail", Boolean.FALSE);
        }
        int i = 0;
        try {
//            getEngine().getOrganization().Reload();
            String sql = "update ot_user set State = '%s' where ObjectId = '%s'";
            i = SqlUtil.doNoQuery(String.format(sql, user.getState(), user.getObjectId()));
            getEngine().getOrganization().Reload();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new RestfulApiResult(200,"success", Boolean.TRUE);
    }

    /**
     * 修改用户状态(批量)
     *
     * @param users
     * @return
     */
    @RequestMapping(value = "/modifyUserStatusByCode", method = RequestMethod.POST)
    @ResponseBody
    public final Object modifyUserStatusByCode(@RequestBody Map<String, Object> users){
        logger.info("修改用户状态,userNoList:"+users.get("userNoList")+"-----State:"+users.get("flag"));
        if(null==users||users.isEmpty()|| StringUtils.isBlank((String)users.get("flag"))||
                StringUtils.isBlank((String)users.get("userNoList"))){
            return new RestfulApiResult(500,"fail", Boolean.FALSE);
        }
        int i = 0;
        try {
//            getEngine().getOrganization().Reload();
            String sql = "update ot_user set State = '%s' where Code in (%s)";
            i = SqlUtil.doNoQuery(String.format(sql, users.get("flag"), getInCond((String)users.get("userNoList"))));
            getEngine().getOrganization().Reload();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new RestfulApiResult(200,"success", Boolean.TRUE);
    }

    @RequestMapping("/test")
    public JSONObject getUser(){
        JSONObject result = new JSONObject();
        logger.info("业务系统获取用户数据———"+ UrlConfig.BusinessUrl);
        result.put("Message","成功");
        result.put("Result",UrlConfig.BPMURL);
        return result;
    }

    /**
     * 拼接IN条件值
     * @param str
     * @return
     */
    public static String getInCond(String str) {
        String[] strArr = str.split(",");
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i < strArr.length; i++){
            if(i == strArr.length-1){
                sb.append("'"+strArr[i]+"'");
            }else{
                sb.append("'"+strArr[i]+"'"+",");
            }
        }
        return sb.toString();
    }
}
